<template>
  <a-modal
    :open="open"
    :title="title"
    :okText="okText"
    :cancelText="cancelText"
    @ok="ok"
    @cancel="cancel"
  >
    <slot name="form"></slot>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, toRefs, provide, PropType } from "vue";
import { ModalFormConig } from "./types";
import { message } from "ant-design-vue";

const emit = defineEmits(["update:open", "ok", "cancel"]);
const props = defineProps({
  /** 配置 */
  config: {
    type: Object as PropType<ModalFormConig<any>>,
    required: true,
  },
  /** 确认按钮文字 */
  okText: {
    type: String,
    default: "确定",
  },
  /** 取消按钮文字 */
  cancelText: {
    type: String,
    default: "取消",
  },
  /** 提示文 */
  title: {
    type: String,
    default: "Tip",
  },
  /** 是否打开组件 */
  open: {
    type: Boolean,
    default: false,
  },
});
const { open } = toRefs(props);

//表单ref
const formRef = ref();

/**
 * 作用于弹窗表单的依赖注入
 */
provide("modal", {
  //获取表单ref
  formRefCallback: (e: any) => {
    formRef.value = e;
  },
});

/**
 * 确定操作
 */
const ok = () => {
  //校验表单
  formRef.value
    .validate()
    .then(() => {
      //触发确定操作
      props.config.ok({
        close: () => {
          //关闭窗口
          emit("update:open", false);
          //清除数据
          formRef.value.resetFields();
        },
      });
    })
    .catch(() => {
      message.warn("请检查是否按要求填写");
    });
};

/**
 * 取消操作
 */
const cancel = () => {
  //清空数据
  formRef.value.resetFields();
  //关闭弹窗
  emit("update:open", false);
  emit("cancel");
};
</script>
<style lang="scss" scoped></style>
